//@ts-nocheck
import React, { useRef, useState } from 'react';
// 引入axios
import server from '@/utlis/server.js';
import {
  Form,
  Input,
  Button,
  Toast,
  NumberKeyboard,
  PasscodeInput,
  Space,
} from 'antd-mobile';
import { history } from 'umi';
import logo from '@/static/猫眼.png';

import styles from './demo1.less';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons';
import '@/pages/golobo.less';
import 'lib-flexible';
import './index.less';
export default function index() {
  // const [value, setValue] = useState('');
  const [visible, setVisible] = useState(false);
  const [qh1, qh2] = useState(false);
  let [refform] = Form.useForm();
  let [refform2] = Form.useForm();
  // 定时器
  let timer = null;
  const [error, setError] = useState(false);
  const onFinish = (value: string) => {
    console.log(value);
  };
  // 用户信息
  let [user, setuser] = useState({
    phone: '',
    email: '',
    password: '',
    code: '',
  });
  // 接受发送回来的验证码
  let [code, setcode] = useState('');
  // 向手机号发送验证码
  let sendphonecode = async (e) => {
    console.log(user);

    if (user.phone == '') {
      Toast.show({
        icon: 'fail',
        content: '手机号不可为空',
      });

      return;
    }
    let sec = 60;
    timer = setInterval(function () {
      var btn = e.target;
      sec--;
      btn.innerHTML = `<span>重新发送(${sec})</span>`;
      if (sec == 0) {
        clearInterval(timer); // 清除定时器
        btn.innerHTML = '<span>重新发送</span>'; // 设置按钮文本
      }
    }, 1000);

    let { data } = await server.post('/phoneapi', { phone: user.phone });
    console.log(data);
    setcode(data.code);

   

  };
  let sendemailcode=async(e)=>{
    console.log(111);
    console.log(user);
    
    if (user.email == '') {
      Toast.show({
        icon: 'fail',
        content: '邮箱不可为空',
      });

      return;
    }
    let sec = 60;
    timer = setInterval(function () {
      var btn = e.target;
      sec--;
      btn.innerHTML = `<span>重新发送(${sec})</span>`;
      if (sec == 0) {
        clearInterval(timer); // 清除定时器
        btn.innerHTML = '<span>重新发送</span>'; // 设置按钮文本
      }
    }, 1000);

    let { data } = await server.post('/apiemail', { email: user.email });
    console.log(data);
    if(data.code){
      setcode(data.code);
  
      }
      Toast.show({
        icon: 'fail',
        content: data.msg
      });
  }
  // 登录
  let login = async (body) => {
    let { data } = await server.post('/logon', body);
    console.log(data);
    if (data.msg) {
      return Toast.show({
        icon: 'fail',
        content: data.msg,
      });
    } else {
      localStorage.setItem('token', data.token);
      history.push('/home');
    }
  };
  let codechange = (_: any, value: MobileValue) => {
    
    if (value == '') {
      return Promise.reject(new Error('手机号不可为空！'));
    } else {
      if (value == code) {
        clearInterval(timer);
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('验证码不一致请重新输入'));
      }
    }
  };
  let checkMobile = (_: any, value: MobileValue) => {
    let phone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
    if (value == '') {
      return Promise.reject(new Error('手机号不可为空！'));
    } else {
      if (phone.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('请输入正确的手机号'));
      }
    }
  };
  let checkemail=(_: any, value: MobileValue) => {
    let email = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
    if (value == '') {
      return Promise.reject(new Error('邮箱不可为空！'));
    } else {
      if (email.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('请输入正确的邮箱号'));
      }
    }
  };
  return (
    <>
      <div className="login">
        <div className="logo">
          <div className="logo_box">
            <img src={logo} alt="电影商务" />
          </div>
          <h3>欢迎登录</h3>
        </div>
        <div className="logo_png"></div>
        <div className="login1">
          {qh1 ? (
            <Form
              layout="horizontal"
              form={refform2}
              footer={
                <div className="sevebtn">
                  <Button
                    block
                    color="primary"
                    size="large"
                    onClick={() => {
                      clearInterval(timer);
                      setuser({
                        phone: '',
                        email: '',
                        password: '',
                        code: '',
                      });
                      qh2(!qh1);
                    }}
                  >
                    切换登录方式
                  </Button>
                  <Button
                    block
                    type="submit"
                    disabled={
                      (user.username != '') & (user.password != '')
                        ? false
                        : true
                    }
                    color="primary"
                    onClick={() => {
                      let users = {
                        username: user.username,
                        password: user.password,
                      };
                      login(users);
                    }}
                    size="large"
                  >
                    登录
                  </Button>
                </div>
              }
            >
              <Form.Item
                name="email"
                label="邮箱"
                rules={[{ required: true, },{validator: checkemail}]}
              >
                <Input
                  value={user.username}
                  onChange={(value) => {
                    user.email = value;
                    setuser({ ...user });
                  }}
                  placeholder="请输入邮箱"
                />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true }, { validator: codechange }]}
                extra={<a onClick={sendemailcode}>发送验证码</a>}
              >
                <Input
                  placeholder="请输入密码"
                  clearable
                  value={user.password}
                  onChange={(value) => {
                    user.password = value;
                    setuser({ ...user });
                  }}
                  type={visible ? 'text' : 'password'}
                />
              </Form.Item>
            </Form>
          ) : (
            <Form
              form={refform}
              layout="horizontal"
              footer={
                <div className="sevebtn">
                  <Button
                    block
                    color="primary"
                    size="large"
                    onClick={() => {
                      clearInterval(timer);
                      setuser({
                        phone: '',
                        email: '',
                        password: '',
                        code: '',
                      });
                      qh2(!qh1);
                    }}
                  >
                    切换登录方式
                  </Button>
                  <Button
                    block
                    type="submit"
                    onClick={() => {
                      refform
                        .validateFields()
                        .then((value) => {
                          login(value);
                        })
                        .catch((err) => {
                          if (err) {
                            return Toast.show({
                              icon: 'fail',
                              content: '登录失败',
                            });
                          }
                        });
                    }}
                    disabled={user.code != '' ? false : true}
                    color="primary"
                    size="large"
                  >
                    登录
                  </Button>
                </div>
              }
            >
              <Form.Item
                name="phone"
                label="手机号"
                rules={[{ required: true }, { validator: checkMobile }]}
              >
                <Input
                  value={user.phone}
                  onChange={(value) => {
                    user.phone = value;
                    setuser({ ...user });
                  }}
                  placeholder="请输入手机号"
                />
              </Form.Item>
              <Form.Item
                label="短信验证码"
                name="code"
                rules={[{ required: true }, { validator: codechange }]}
                extra={<a onClick={sendphonecode}>发送验证码</a>}
              >
                <Input
                  placeholder="请输入"
                  value={user.code}
                  onChange={(value) => {
                    user.code = value;
                    setuser({ ...user });
                  }}
                />
              </Form.Item>
            </Form>
          )}
          {/* {qh1 ? (
            <Form form={refform} initialValues={user}
            onFinish={onFinish}>
              <Form.Item label="用户名" name='username' rules={[{required:true,message: '用户名不能为空'}]}>
                <Input key="1" placeholder="请输入用户名"  clearable />
              </Form.Item>
              <Form.Item
                label="密码"
                extra={
                  <div className={styles.eye}>
                    {!visible ? (
                      <EyeInvisibleOutline onClick={() => setVisible(true)} />
                    ) : (
                      <EyeOutline onClick={() => setVisible(false)} />
                    )}
                  </div>
                }
              >
                <Input
                  placeholder="请输入密码"
                  clearable
                  type={visible ? 'text' : 'password'}
                />
              </Form.Item>
            </Form>
          ) : (
            <Form>
              <Form.Item label="手机号" rules={[{ required:true,message: '手机号不能为空' },{ validator: checkMobile }]}>
                <Input key="2" placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item
                label="短信验证码"
                extra={
                  <div className={styles.extraPart}>
                    <a>发送验证码</a>
                  </div>
                }
              >
                <PasscodeInput keyboard={<NumberKeyboard />} />
              </Form.Item>
            </Form>
          )} */}
        </div>
      </div>
    </>
  );
}
